﻿namespace ApiTemplate.WebApi.Controllers.Base
{
    /// <summary>
    /// 基础的api控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BaseApiController : ControllerBase
    {
        /// <summary>
        /// 缓存相关
        /// </summary>
        public ICacheHelper CacheHelper { get; set; }

        /// <summary>
        /// 注入映射对象
        /// </summary>
        public IMapper Mapper { get; set; }

        /// <summary>
        /// 当前用户
        /// </summary>
        public ICurrentUser CurrentUser { get; set; }

        /// <summary>
        /// 获取真实IP
        /// </summary>
        /// <returns></returns>
        protected string GetRealIp()
        {
            string ip;
            if (Request.Headers.ContainsKey("X-Forwarded-For"))
            {
                ip = Request.Headers["X-Forwarded-For"];
            }
            else if (Request.Headers.ContainsKey("X-Real-IP"))
            {
                ip = Request.Headers["X-Real-IP"];
            }
            else
            {
                ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            }
            return ip;
        }

        /// <summary>
        /// 获取当前访问的设备类型
        /// </summary>
        /// <returns></returns>
        protected DeviceType GetDeviceType()
        {
            DeviceType deviceType = DeviceType.Unknown;
            if (Request.Headers.ContainsKey("DeviceType"))
            {
                string deviceTypeStr = Request.Headers["DeviceType"];
                deviceType = (DeviceType)deviceTypeStr.ToInt32();
            }
            return deviceType;
        }
    }
}
